package demoobj;

import java.util.Objects;

/**
 * @author: knowno
 * @create: 2025-09-12 10:37
 * @Version 1.0
 **/
public class CloneApple{

    public static void main(String[] args) throws CloneNotSupportedException {
        Apple apple = new Apple();
        apple.setName("苹果17");
        apple.setPrice(100);
        apple.setColor("红色");
        System.out.println(apple);

        //克隆了一份出来
        Apple apple1 = (Apple) apple.clone();
        System.out.println(apple1);

        //使用equals方法比较一下(Apple类中对equals方法进行了重写)
        System.out.println(apple.equals(apple1));

        //如果我们修改了一个对象的属性,是否会影响到另一个对象的属性
        apple1.setName("苹果12");
        System.out.println(apple);
        System.out.println(apple1);


    }


}

/**
 * 1. 实现Cloneable接口
 * 2. 重写clone方法
 * 3. 调用super.clone()
 */
class  Apple  implements  Cloneable{
    private  String name;
    private  int price;
    private  String color;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    public Apple() {
    }

    public Apple(String name, int price, String color) {
        this.name = name;
        this.price = price;
        this.color = color;
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }

    @Override
    public String toString() {
        return "Apple{" +
                "name='" + name + '\'' +
                ", price=" + price +
                ", color='" + color + '\'' +
                '}';
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }

        Apple apple = (Apple) o;

        if (price != apple.price) {
            return false;
        }
        if (!Objects.equals(name, apple.name)) {
            return false;
        }
        return Objects.equals(color, apple.color);
    }

    @Override
    public int hashCode() {
        int result = name != null ? name.hashCode() : 0;
        result = 31 * result + price;
        result = 31 * result + (color != null ? color.hashCode() : 0);
        return result;
    }
}
